package com.yummy.web.config;

import java.io.IOException;
import java.util.Date;

import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.util.TypeUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class WebMvcConfiguration implements WebMvcConfigurer {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        Jackson2ObjectMapperBuilderCustomizer cunstomizer = new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                jacksonObjectMapperBuilder.serializerByType(Long.class, new JsonSerializer<Long>() {

                    @Override
                    public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers)
                            throws IOException {
                        if (value == null) {
                            gen.writeNull();
                            return;
                        }
                        String candi = String.valueOf(value);
                        if (candi.length() <= 15) {
                            gen.writeNumber(value);
                            return;
                        }
                        gen.writeString(candi);
                    }

                });
            }
        };
        return cunstomizer;
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(Object.class, Date.class, new Converter<Object, Date>() {

            @Override
            public Date convert(Object source) {
                return TypeUtils.castToDate(source);
            }

        });
    }

}
